//
//  AddAdminViewController.swift
//  VenusMaster
//
//  Created by weimengran on 2019/1/2.
//  Copyright © 2019 zhaowang. All rights reserved.
//

import UIKit

class AddHeaderView: UIView {
    let  searchBar = UISearchBar.init()
    override init(frame: CGRect) {
        super.init(frame: frame)
        addSubview(searchBar)
        searchBar.snp.makeConstraints { (make) in
            make.left.equalTo(self).offset(8)
            make.right.equalTo(self).offset(-8)
            make.centerY.equalTo(self)
            make.height.equalTo((44))
        }
        searchBar.placeholder = "点击搜索名称"
    }
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
}





class AddAdminViewController: BaseViewController {

    var groupId : Int = 0
    
    var pageNo : Int = 1
    
    let tableView = UITableView.init(frame: CGRect.zero, style: .grouped)
    
    let headerView = AddHeaderView.init(frame: CGRect.init(x: 0, y: 0, width: LayoutCommon.width, height: 50))
    
    var groupVC : MyGroupAdminListVC?
    
    var dataAry : [TopicGroupModel] = [TopicGroupModel]()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        title = "添加管理员"
        view.addSubview(tableView)
        tableView.delegate = self
        tableView.dataSource = self
        tableView.snp.makeConstraints { (make) in
            make.top.equalTo(navgationBar.snp.bottom)
            make.left.right.bottom.equalToSuperview()
        }
        headerView.backgroundColor = UIColor.white
        tableView.tableHeaderView = headerView
        // Do any additional setup after loading the view.
        
        self.loadData(page: self.pageNo, text: "")
    }
    
    func loadData(page:Int,text: String) {
        let dict = [
            "operatorId":String(UserInfo.shareInstance.userModel().id),
            "groupId":String(groupId),
            "pageNo":self.pageNo,
            "pageSize":10,
            "timestamp":1,
            "sign": 1] as [String : Any]
        NetworkTools.shareInstance.loadData(.get, URLString: kqueryGroupUserList, parameters: dict) {[weak self] (data, isResult) in
            if !isResult {
                guard let resultDict = data as? [String : NSObject] else { return }
                guard let dataArray = resultDict["data"] as? [NSObject] else { return }
                let groupModels = TopicGroupModel.tmSpeelBreakModelArr(dataArray)
                let groupModels1 : [TopicGroupModel] = ((groupModels as? [TopicGroupModel])?.filter{(topicModel) -> Bool in
                    return topicModel.user != nil
                    })!
                if self?.pageNo == 1 {
                    self?.dataAry = groupModels1
                }else{
                    self?.dataAry.append(contentsOf: groupModels1)
                }
                
                self!.tableView.reloadData()
            }
            
        }
    }
    func addAdmin(model : TopicGroupModel) {
        let dict = [
            "operatorId":String(UserInfo.shareInstance.userModel().id),
            "timestamp":1,
            "sign": 1,
            ] as [String : Any]
        let string = dict.formatApi()
        let paramer = model.json()
        TempNetTool.post(kHost+kaddAdminToGroupList+string, parameters: dict, progress: nil, success: {[weak self] (result) in
            self?.hudLoadMessage("添加成功")
            self?.groupVC?.groupList.insert(model, at: 0)
            self?.groupVC?.tableView.reloadData()
            self?.navigationController?.popViewController(animated: true);
            
        }) { (error) in
            self.hudLoadMessage(error?.localizedDescription ?? "网络请求出错");
        }


            
        
    }
    
    
    
}
extension AddAdminViewController : UITableViewDelegate,UITableViewDataSource {
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return self.dataAry.count
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell: UITableViewCell = {
            guard let cell = tableView.dequeueReusableCell(withIdentifier: "kCellID") else {
                // Never fails:
                return UITableViewCell(style: UITableViewCell.CellStyle.subtitle, reuseIdentifier: "kCellID")
            }
            return cell
        }()
        let model = dataAry[indexPath.row];
        cell.textLabel?.text = (model.user!["userName"] as! String);
        cell.textLabel?.font = UIFont.systemFont(ofSize: 18)
        if ((model.user?["updateTime"] as? NSString) != nil) {
            cell.detailTextLabel?.text = String.timeToString(time: (model.user?["updateTime"] as? NSString)!.integerValue)
        } else {
            cell.detailTextLabel?.text = "yyyy-MM-dd"
        }
        cell.detailTextLabel?.textColor = UIColor.gray
        cell.imageView!.kf.setImage(with: URL(string: model.user!["headImg"] as! String), placeholder: UIImage.init(named: "defalut_avatar"), options: [.cacheMemoryOnly], progressBlock: nil, completionHandler: nil);

        cell.imageView!.kf.setImage(with: URL(string: model.user!["headImg"] as! String), placeholder: UIImage.init(named: "defalut_avatar"), options: [.cacheMemoryOnly], progressBlock: nil, completionHandler: nil);
        cell.imageView?.layer.masksToBounds = true
        cell.width = 50;
        cell.height = 50;
        cell.imageView?.layer.cornerRadius = 25;
        cell.selectionStyle = .none
        return cell
    }
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return 60
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        self.addAdmin(model: self.dataAry[indexPath.row])
    }
}
